$(
    function () {
        if (isOpenAjax) {
            SetUpAjaxLoading('init');
        }
        else {
            $("a[overrideClick]").click(
				function () {
				    return ElementsClick(this);
				}
			);
        }
        $("#txtPrice1").blur(function () {
            CheckNumber($(this));
        })
        $("#txtPrice2").blur(function () {
            CheckNumber($(this));
        })
        $("#txtPage").blur(function () {
            CheckNumber($(this));
        })
        GetAreaHotComment();
        ProcessLastView();
        GetRecommend();
    }
);

function SetUpAjaxLoading(type) {
    try {
        var links = $("#mainDiv").find("[canAjax=1]");
        if (links && links.length > 0) {
            links.unbind("click");
            links.each(function () {
                var cur = $(this);
                cur.click(
					function () {
					    var toAjax = true;
					    if (cur.attr("overrideClick") != null && cur.attr("overrideClick") == 1) {
					        toAjax = ElementsClick(this);
					    }
					    if (cur.attr("pos") != null && cur.attr("pos") == "bottom") {
					        hashInfo.pos = "bottom";
					    }
					    else {
					        hashInfo.pos = "";
					    }
					    if (toAjax) {
					        DoAjax(cur.attr("href"), cur.attr("anchor"));
					    }
					    return false;
					}
				);
            });
        }
    }
    catch (ex) {
        var targetUrl = hashInfo.url;
        if (type == "init") {
            targetUrl = window.location.href;
        }
        AddJsErrorLog(targetUrl, "SetUpAjaxLoading" + type, "message:" + ex.message + ";lineNumber:" + ex.lineNumber);
    }
}

function DoAjax(url, anchorName) {
    try {
        url = $.trim(url);
        if (anchorName != "" && anchorName != null && typeof (anchorName) != "undefined") {
            var tmpIndex = url.toLowerCase().indexOf(".m18.com/") + 8;
            url += "#" + url.substring(tmpIndex + 1, url.length - 4) + "-" + anchorName;
        }
        BuildAjaxLink(url);
        if (hashInfo.current != hashInfo.target && hashInfo.url.length > 0) {
            var h = $("#J_lazyload").height();
            $(".loadingmask").css("height", h);
            $(".loadingmask-bg").css("height", h);
            $(".loadingmask").show();
            $(".fixtop").show();
            $.ajax(
			{
			    type: "get",
			    url: hashInfo.url,
			    //cache: false,
			    //tt: new Date(),
			    data: null,
			    dataType: "json",
			    async: true,
			    contentType: "application/json; charset=utf-8",
			    success: function (result) {
			        try {
			            // 更新数据
			            UpdateUI(result);
			            hashInfo.current = hashInfo.target;
			            hashInfo.Repeatflag = true;
			            // 维护Filter展开（收起）区域
			            BindFilterToggle();
			            if (isOpenAjax) {
			                SetUpAjaxLoading('ajaxInit');
			            }
			            else {
			                $("a[overrideClick]").unbind("click");
			                $("a[overrideClick]").click(
							function () {
							    return ElementsClick(this);
							}
						);
			            }
			            $("#txtPrice1").blur(function () {
			                CheckNumber($(this));
			            })
			            $("#txtPrice2").blur(function () {
			                CheckNumber($(this));
			            })
			            $("#txtPage").blur(function () {
			                CheckNumber($(this));
			            })
			            // 维护Hash
			            if (hashInfo.anchor != null
						&& hashInfo.anchor != "") {
			                var windowHash = window.location.hash;
			                var toHash = hashInfo.current + "-" + hashInfo.anchor;
			                if (windowHash == null) {
			                    windowHash = "";
			                }
			                if (windowHash.indexOf("#") >= 0) {
			                    windowHash = windowHash.replace(/#/g, "");
			                }
			                var targetAnchor = hashInfo.current + "_" + hashInfo.anchor;
			                var targetObject = $("#" + targetAnchor);
			                if (toHash != windowHash
							&& targetObject.length > 0) {
			                    window.location.hash = toHash;
			                }
			                if (targetObject.length > 0) {
			                    ScrollToTargetAnchor(targetAnchor);
			                }
			            }
			            if (typeof (LazyLoad) == "undefined" || LazyLoad == null) {
			                ImportScriptionFile("http://img.m18.com/web/j/app/comm/lazyLoad.js");
			                setTimeout("new LazyLoad('#J_lazyload')", 500);
			            }
			            else new LazyLoad('#J_lazyload');
			        }
			        catch (ex) {
			            $(".loadingmask").hide();
			            AddJsErrorLog(hashInfo.url, "DoAjaxSuccess", "message:" + ex.message + ";lineNumber:" + ex.lineNumber);
			            setTimeout("RefreshTargetUrl()", 500);
			        }
			    },
			    error: function (result, status) {
			        $(".loadingmask").hide();
			        try {
			            var content = "";
			            var start = result.responseText.search("<title>") + 7;
			            var end = result.responseText.search("</title>");
			            if (start > 0 && end > 0) {
			                content = result.responseText.substring(start, end);
			            }
			            start = result.responseText.search("<code><pre>") + 11;
			            end = result.responseText.search("</pre></code>");
			            if (start > 0 && end > 0) {
			                content += result.responseText.substring(start, end);
			            }
			            AddJsErrorLog(hashInfo.url, "DoAjaxAjax", "status:" + status + ";Contetn:" + content + ";Content-Type:" + (result.getResponseHeader("content-type") ? result.getResponseHeader("content-type") : ""));
			        }
			        catch (ex) { }
			        setTimeout("RefreshTargetUrl()", 500);
			    }
			});
        }
    }
    catch (ex) {
        AddJsErrorLog(url, "DoAjax", "message:" + ex.message + ";lineNumber:" + ex.lineNumber);
    }
    return false;
}

function RefreshTargetUrl() {
    var host = window.location.host;
    window.location.href = "http://" + host + "/" + hashInfo.target + ".htm";
}

function UpdateUI(data) {
    var html = "";
    if (typeof (data) == "undefined" || data == null) {
        return;
    }
    //1.如果用户是点翻页，排序等操作，只更新排序，商品和分页区域
    html += BuildFilterArea(data) + "\r\n";
    html += BuildSortUI(data.SortUI) + "\r\n";
    html += BuildStyleUI(data.StyleUI) + "\r\n";
    html += BuildPageUI(data.PageUI);
    ChangePageTitle(data.PageTitle);
    $("#mainDiv").find("[ajaxContent=1]").remove();
    var newContent = $(html);
    var pos = $("#ajaxContentPosition");
    pos.after(newContent);
}

function BuildPageUI(pageUI) {
    var html = "";
    if (pageUI.PageCount > 1) {
        html += "<div ajaxContent=\"1\" class=\"cf mt10 mb10\">"
			+ "<div class=\"paging-skip fr\">"
			+ "<div class=\"fl ml10\"><span class=\"paging-txt\">到第</span>"
			+ "<input type=\"text\" id=\"txtPage\" class=\"paging-text\" value=\"" + pageUI.JumpPageIndex + "\" />"
			+ "<span class=\"paging-txt\">页 </span><a pos=\"bottom\" overrideClick=\"1\" canAjax=\"1\" id=\"subPage\" class=\"paging-btn\" href=\"" + pageUI.JumpUrl + "\" anchor='Sort'><span>确定</span></a>"
        + "</div>"
		+ "</div>";

        html += "<div class=\"paging fr\">";
        if (pageUI.PrePageLink != null && pageUI.PrePageLink.IsShow) {
            html += "<a id=\"" + pageUI.PrePageLink.InnerName + "\" pos=\"bottom\" canAjax=\"1\" class=\"paging-prev\" anchor='Sort' href=\"" + pageUI.PrePageLink.Url + "\"><span>" + pageUI.PrePageLink.Text + "</span></a>";
        }

        for (var i = 0; i < pageUI.PageLinks.length; i++) {
            var page = pageUI.PageLinks[i];
            if (page.Url != null && page.Url != "") {
                html += "<a pos=\"bottom\" canAjax=\"1\" anchor='Sort' href=\"" + page.Url + "\"><span>" + page.Text + "</span></a>";
            }
            else {
                html += "<span class=\"" + (page.Text == "..." ? "paging-break" : "cur") + "\">" + page.Text + "</span>";
            }
        }
        if (pageUI.NextPageLink != null && pageUI.NextPageLink.IsShow) {
            html += "<a id=\"" + pageUI.NextPageLink.InnerName + "\" pos=\"bottom\" canAjax=\"1\" class=\"paging-next\" anchor='Sort' href=\"" + pageUI.NextPageLink.Url + "\"><span>" + pageUI.NextPageLink.Text + "</span></a>";
        }
        html += "</div>";
        html += "</div>";
    }
    return html;
}

function BuildStyleUI(styleUI) {
    var html = "";
    if (styleUI.SeeAllLink != null) {
        html += "<div ajaxContent=\"1\" class=\"warntxt\">抱歉，没有找到符合条件的商品！<a class=\"a2 underline\" canAjax=\"1\" anchor='Sort' href=\"" + styleUI.SeeAllLink.Url + "\">" + styleUI.SeeAllLink.Text + "</a></div>";
    }
    if (styleUI != null
		&& styleUI.Styles != null
		&& styleUI.Styles.length > 0) {
        html += "<div ajaxContent=\"1\" class=\"itemmain mb20 relative\" name=\"__FLLB002\">"
			+ "<ul class=\"list list-n4\" id=\"J_lazyload\">";
        var imgAttributeName = "src";
        for (var i = 0; i < styleUI.Styles.length; i++) {
            if (i >= 12) {
                imgAttributeName = "lazyload";
            }
            var style = styleUI.Styles[i];
            var aliasname = "";
            if (style.AliasName != undefined && style.AliasName != null && style.AliasName != "") {
                aliasname = style.AliasName;
            }
            html += "<li styleId=\"" + style.StyleId + "\" class=\"item item-sale\">";
            html += "<a target=\"_blank\" href=\"" + style.Url + "\" title=\"" + style.ChineseName + " " + aliasname + "\" class=\"item-desc ForSkuLink\">"
				+ "<img title=\"" + style.ChineseName + " " + aliasname + "\" " + imgAttributeName + "=\"" + style.ImageUrl + "\" alt=\"" + style.ChineseName + "\" width=\"175\" height=\"228\" />"
				+ "<span class=\"item-price\"><em>" + style.WebSalePrice + "</em>";
            if (style.GPPrice != null && style.GPPrice != "") {
                html += "<span class=\"item-points\">+" + style.GPPrice + "积分</span>";
            }

            html += "</span>";

            if (style.OriginalPrice != null && style.OriginalPrice != "") {
                html += "<del>" + style.OriginalPrice + "</del>";
            }
            html += "<span class=\"item-title\">" + style.ShortChineseName;

            if (style.AliasName != null && style.AliasName != "") {
                html += "&nbsp;<em>" + style.AliasName + "</em>";
            }

            html += "</span>"
				+ "</a>";
            if (style.Skus != null
				&& style.Skus.length > 1) {
                html += "<div name=\"__ColorImg\">"
				+ "<ul class=\"item-color SkuColorSelect\">";
                for (var j = 0; j < style.Skus.length; j++) {
                    var sku = style.Skus[j];
                    html += "<li>"
								+ "<a rel=\"nofollow\" imgName=\"" + sku.StyleImageUrl + "\" skuId=\"" + sku.SKUDimentionId1 + "\" alt=\"" + sku.SKUDimentionName1 + "\" title=\"" + sku.SKUDimentionName1 + "\" href=\"javascript:SKUChangeBind('" + sku.StyleId + "', '" + sku.SKUDimentionId1 + "');\">"
								+ "<img alt=\"" + sku.SKUDimentionName1 + "\" " + imgAttributeName + "=\"" + sku.ImageUrl + "\" />"
								+ "</a>"
						+ "</li>";
                }
                html += "</ul>"
					+ "</div>";
            }
            if (style.IsShowComment) {
                html += "<div class=\"item-rate\">"
				+ "<div class=\"score-s\"><span class=\"score-s-star\" style=\"" + style.CommentInnerCss + "\"></span></div>"
				+ "<span class=\"item-rate-num\">(<a id=\"PLTS004\" href=\"" + style.Url + "#comment\" target=\"_blank\" class=\"CommSkuLink\">共" + style.CommentCount + "条</a>)</span>"
				+ "</div>";
            }
            html += "<p class=\"item-brand\">" + style.TradeMarkName + "</p>";
            if (style.SpecialPriceFlag) {
                html += "<p class=\"item-tag\">特价</p>";
            }
            html += "</li>";
        }
        html += "</ul>"
			+ "<div class=\"loadingmask\">"
   					+ "<div class=\"loadingmask-bg\"></div>"
    				+ "<div class=\"loadingmask-txt fixtop\"><img src=\"http://img.m18.com//asset/misc/i/loading-pink.gif\" class=\"mr10\" style=\"vertical-align:middle\"></div>"
				+ "</div>"
				+ "</div>";
    }
    return html;
}

function BuildFilterArea(data) {
    var html = "";
    if ((data.ChoiceUI.Choices != null && data.ChoiceUI.Choices.length > 0) || (data.TradeMarkUI.TradeMarks != null && data.TradeMarkUI.TradeMarks.length > 0) || (data.PropertyUI.Properties != null && data.PropertyUI.Properties.length > 0)) {
        html += "<div ajaxContent=\"1\" id=\"" + hashInfo.target + "_Filter" + "\" class=\"proditembox mb20\">"
			+ "<div id='Filter'></div>"
            + "<div class=\"termlist bor1\">";
        if (data.ChoiceUI.Choices != null
		&& data.ChoiceUI.Choices.length > 0) {
            html += "<div class=\"choice-item cf\">"
				+ "<div class=\"cititle\">已选：</div>"
				+ "<div class=\"choice-item-list\">";
            for (var i = 0; i < data.ChoiceUI.Choices.length; i++) {
                var curChoice = data.ChoiceUI.Choices[i];
                html += "<a canAjax=\"1\" anchor='Filter' href=\"" + curChoice.Link.Url + "\">" + curChoice.Link.Text;
                if (curChoice.AliasName != null
				&& curChoice.AliasName != "" && curChoice.AliasName != curChoice.Link.Text) {
                    html += "<em>&nbsp;" + curChoice.AliasName + "</em>";
                }
                html += "</a>";
            }
            html += "</div>"
            if (data.ChoiceUI.CleanLink != null) {
                html += "<div class=\"delect-btn fr\"><a canAjax=\"1\" anchor='Filter' href=\"" + data.ChoiceUI.CleanLink.Url + "\">" + data.ChoiceUI.CleanLink.Text + "</a></div>";
            }
            html += "</div>";
        }

        if (data.TradeMarkUI.TradeMarks != null &&
		data.TradeMarkUI.TradeMarks.length > 0) {
            var tm = data.TradeMarkUI.TradeMarks[i];
            html += "<div class=\"prop-item branditem pr10\">"
					+ "<dl class=\"cf\">"
					+ "<dt title=\"品牌\">品牌：</dt>"
					+ "<dd class=\"cf\">";
            if (data.TradeMarkUI.AllLink != null) {
                html += "<a canAjax=\"1\" anchor='Filter' href=\"" + data.TradeMarkUI.AllLink.Url + "\" title=\"" + data.TradeMarkUI.AllLink.Text + "\" class=\"allbtn" + (data.TradeMarkUI.AllLink.IsCurrent ? " cur" : "") + "\">" + data.TradeMarkUI.AllLink.Text + "</a>";
            }
            html += "<ul class=\"cf brandBox\">";
            for (var i = 0; i < data.TradeMarkUI.TradeMarks.length; i++) {
                var tm = data.TradeMarkUI.TradeMarks[i];
                html += "<li style=\"" + (tm.Link.IsShow ? "" : "display:none;") + "\">"
					+ "<a canAjax=\"1\" " + (tm.Link.IsCurrent ? " class=\"cur\"" : "") + " title=\"" + tm.TradeMarkName + "\" anchor='Filter' href=\"" + tm.Link.Url + "\">"
					+ "<span class=\"brandname\">" + tm.TradeMarkName + "</span><span class=\"brandimg\" style=\"background:url(http://img.m18.com/web/pic/list/brand/" + tm.TradeMarkId + "_m.gif)\"></span>"
					+ "</a>"
					+ "</li>";
            }
            html += "</ul>"
					+ "</dd>"
					+ "</dl>"
					+ "</div>";
        }

        if (data.PropertyUI.Properties != null && data.PropertyUI.Properties.length > 0) {
            html += "<div id=\"propretyArea\" name=\"__pro_shuxing\">";
            for (var i = 0; i < data.PropertyUI.Properties.length; i++) {
                var pro = data.PropertyUI.Properties[i];
                html += "<div class=\"prop-item pr10 proTypeBox\" style=\"" + (pro.IsShow ? "" : "display:none;") + "\">"
				+ "<dl class=\"cf\">"
				+ "<dt title=\"" + pro.DisplayName + "\">" + pro.DisplayName + "：</dt>"
				+ "<dd>"
				+ "<a canAjax=\"1\" anchor='Filter' href=\"" + pro.AllValue.Url + "\" valueId=\"0\" title=\"" + pro.AllValue.Text + "\" class=\"allbtn" + (pro.AllValue.IsCurrent ? " cur" : "") + "\">" + pro.AllValue.Text + "</a>"
				+ "<ul class=\"cf\" typeId=\"" + pro.TypeId + "\">";
                if (pro.Values != null && pro.Values.length > 0) {
                    for (var j = 0; j < pro.Values.length; j++) {
                        var pv = pro.Values[j];
                        html += "<li style=\"" + (pv.IsShow ? "" : "display:none;") + "\"><a canAjax=\"1\" anchor='Filter' href=\"" + pv.Url + "\" valueId=\"\" title=\"" + pv.Text + "\" class=\"" + (pv.IsCurrent ? "cur" : "") + "\">" + pv.Text + "</a></li>";
                    }
                }
                html += "</ul>"
			+ "</dd>"
			+ "</dl>"
			+ "</div>";
            }
            html += "</div>";
        }
        html += "</div>"
		+ "</div>";
    }
    return html;
}

function BuildSortUI(sort) {
    var html = "";
    if (sort.SortLinks == null || sort.SortLinks.length == 0) {
        return html;
    }
    html += "<div ajaxcontent=\"1\" class=\"filterbox cf mb20\">";
    html += "<div id='Sort'></div>";
    html += "<div class=\"cf list-mode\" id=\"" + hashInfo.target + "_Sort" + "\">"
			+ "<div class=\"fl et\">"
			+ "<div class=\"filter-title\">排序：</div>"
			+ "<ul class=\"fl mr10\">";
    for (var i = 0; i < sort.SortLinks.length; i++) {
        var sortLink = sort.SortLinks[i];
        if (sort.SortLinks[i].IsShow) {
            var sortTitle = "";
            if (sortLink.InnerTitle != null && sortLink.InnerTitle != "") {
                sortTitle = "title=\"" + sortLink.InnerTitle + "\" ";
            }
            html += "<li class=\"" + sortLink.InnerCss + "\" ><a rel=\"nofollow\" canajax=\"1\" id=\"" + sortLink.InnerName + "\" anchor='Sort' href=\"" + sortLink.Url + "\" class=\"" + (sortLink.IsCurrent ? "cur" : "") + "\" " + sortTitle + "><span>" + sortLink.Text + "</span></a></li>";
        }
    }
    html += "</ul>"
			+ "<div class=\"fl mr5\">"
			+ "<input name=\"\" type=\"text\" class=\"mtext priceTxt\" id=\"txtPrice1\" maxlength=\"6\" value=\"" + sort.MinPrice + "\" />"
			+ "<span class=\"lower\">-</span>"
			+ "<input name=\"\" type=\"text\" class=\"mtext priceTxt\" id=\"txtPrice2\" maxlength=\"6\" value=\"" + sort.MaxPrice + "\" />"
			+ "</div>"
			+ "<a canajax=\"1\" overrideClick=\"1\" class=\"mbtn\" id=\"SubPrice\" id=\"JGQJ\" oriHref=\"" + sort.PriceComfirmLink.Url + "\" anchor='Sort' href=\"" + sort.PriceComfirmLink.Url + "\"><span>确定</span></a>"
			+ "</div>"
			+ "<div class=\"paging fr\">";
    if (sort.PageCount > 1) {
        html += "<span class=\"fl mr5 mt5 c9\">" + sort.PageIndex + "/" + sort.PageCount + "</span>";
    }
    if (sort.PrePageLink != null && sort.PrePageLink.IsShow) {
        html += "<a id=\"" + sort.PrePageLink.InnerName + "\" canajax=\"1\" class=\"paging-prev\" anchor='Sort' href=\"" + sort.PrePageLink.Url + "\"><span>" + sort.PrePageLink.Text + "</span></a>";
    }
    if (sort.NextPageLink != null && sort.NextPageLink.IsShow) {
        html += "<a id=\"" + sort.NextPageLink.InnerName + "\" canajax=\"1\" class=\"paging-next\" anchor='Sort' href=\"" + sort.NextPageLink.Url + "\"><span>" + sort.NextPageLink.Text + "</span></a>";
    }
    html += "</div>";
    html += "</div>";
    if (sort.ItemTypeLinks != null && sort.ItemTypeLinks.length > 0) {
        html += "<div class=\"list-view mt10 pb5 cf\">"
						+ "<div class=\"filter-title\">显示：</div>"
						+ "<ul>";
        for (var i = 0; i < sort.ItemTypeLinks.length; i++) {
            var typeLink = sort.ItemTypeLinks[i];
            if (typeLink.IsShow) {
                html += "<li name=\"\"><a rel=\"nofollow\" canajax=\"1\" anchor='Sort' href=\"" + typeLink.Url + "\" class=\"" + (typeLink.IsCurrent ? "cur" : "") + "\" id=\"" + typeLink.InnerName + "\">" + typeLink.Text + "</a></li>";
            }
        }
        html += "</ul>";
        html += "</div>";
    }
    html += "</div>";
    return html;
}

function BuildAjaxLink(link) {
    hashInfo.target = "";
    hashInfo.anchor = "";
    hashInfo.url = "";
    if (link == null
		|| link.length == 0) {
        return;
    }

    //var currentHash
    var tmp = "";
    var tmpIndex = link.indexOf("#");
    if (tmpIndex >= 0) {
        tmp = link.substring(tmpIndex + 1);
    }
    tmpIndex = tmp.lastIndexOf("-");

    if (tmpIndex >= 0) {
        hashInfo.target = tmp.substring(0, tmpIndex);
        hashInfo.anchor = tmp.substring(tmpIndex + 1);
    }
    else {
        hashInfo.target = hashInfo.init;
        hashInfo.anchor = "";
    }
    if (hashInfo.current != ""
		&& hashInfo.target != ""
		&& hashInfo.current != hashInfo.target) {
        var tempAnchorIndex=hashInfo.anchor.indexOf("?");
        if (tempAnchorIndex >= 0) {
            hashInfo.anchor = hashInfo.anchor.substring(0, tempAnchorIndex);
        }
        var index = link.toLowerCase().indexOf("m18.com/") + 7;
        hashInfo.url = link.substring(0, index + 1) + "Service/" + hashInfo.target + "-" + (hashInfo.anchor == "" ? "Filter" : hashInfo.anchor) + ".htm";
    }
}

function GetRecommend() {
    var id1 = styleClassInfo.ClassId1 == null ? "" : styleClassInfo.ClassId1;
    var id2 = styleClassInfo.ClassId2 == null ? "" : styleClassInfo.ClassId2;
    var id3 = styleClassInfo.ClassId3 == null ? "" : styleClassInfo.ClassId3;
    //1.获取量体选衣推荐商品，如果有结果，则随机显示一件，无结果则显示量体选衣入口
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=UTF-8",
        url: "http://myshishang.m18.com/Service/MyStyleService.ashx",
        data: "classId1=" + id1 + "&classId2=" + id2 + "&classId3=" + id3 + "&topN=" + 5 + "&Method=GetTopSellWellStyleByClassId",
        dataType: "jsonp",
        jsonp: "jsoncallback",
        success: function (result) {
            if (result
					&& result.StyleInfoList
					&& result.StyleInfoList.length > 0) {
                var len = result.StyleInfoList.length;
                var iIndex = parseInt(Math.random() * 100 % len);
                $(result.StyleInfoList).each(function (index, item) {
                    if (index == iIndex) {
                        var content = '<div class="item-m item-cont">' +
		                            '<a target="_blank" href="http://www.m18.com/app/AdEntrance.aspx?from=GXTJ04&amp;targetURL=http://product.m18.com/p-' + item.StyleId + '.htm" title="' + item.ChineseName + '"><img height="120" width="92" src="' + item.ImageFileName + '" alt="" class="item-m-pic"/>' +
	                                '<span class="item-m-title">' + item.ChineseName + '</span></a>' +
		                            '<p class="item-m-price"><span>' + item.WebSalePrice + '</span></p>' +
	                                '</div>';
                        $("#divChooseClothes").after(content);
                        $("#chooesClothes1").hide();
                        $("#chooesClothes2").show();
                    }
                });
            }
            else {
                $("#chooesClothes1").show();
                $("#chooesClothes2").hide();
            }
        }
    });
    //2.获取根据用户购买记录计算的推荐商品
    $.ajax({
        type: "GET",
        contentType: "application/json",
        url: "http://productutil.m18.com/IndividualRecommend.aspx",
        data: "Operation=GetRecommendForUser",
        dataType: "jsonp",
        success: function (result) {
            if (result
					&& result.IsSuccess
					&& result.ReturnValue
					&& result.ReturnValue.length > 0) {
                FillStyles(result.ReturnValue);
            }
            else {
                var ids = ""
                if (typeof ($.cookie("LastView")) != "undefined"
					&& $.cookie("LastView") != null) {
                    //获取cookie
                    var viewedItemArray = $.cookie("LastView").split("$");
                    //1. 读取Cookie
                    //获取每次浏览记录的数组
                    var viewedItemRetunArray = new Array();
                    //使用Ajax方式
                    //构建Ajax请求的参数
                    for (var i in viewedItemArray) {
                        //若当前浏览记录为空，则跳过进行下次循环
                        if (viewedItemArray[i] == null
							|| viewedItemArray[i] == "") {
                            continue;
                        }
                        ids += viewedItemArray[i] + ",";
                    }
                    if (ids.length > 0) {
                        ids = ids.substring(0, ids.length - 1);
                    }
                }
                $.ajax({
                    //3.获取根据用户浏览记录计算的推荐商品
                    type: "GET",
                    contentType: "application/json",
                    url: "http://productutil.m18.com/IndividualRecommend.aspx",
                    data: "Operation=GetRecommendForStyles&StyleIds=" + ids,
                    dataType: "jsonp",
                    success: function (result) {
                        if (result
							&& result.IsSuccess
							&& result.ReturnValue
							&& result.ReturnValue.length > 0) {
                            FillStyles(result.ReturnValue);
                        }
                        else {
                            $.ajax({
                                //4.获取根据女装推荐商品
                                type: "GET",
                                contentType: "application/json",
                                url: "http://productutil.m18.com/IndividualRecommend.aspx",
                                data: "Operation=GetBackUpStyles&ClassId1=N1&ShowCount=6&PageSize=60&PageIndex=2",
                                dataType: "jsonp",
                                success: function (result) {
                                    if (result
										&& result.IsSuccess
										&& result.ReturnValue
										&& result.ReturnValue.length > 0) {
                                        FillStyles(result.ReturnValue);
                                    }
                                    else {
                                        FillStyles(null);
                                    }
                                }
                            });
                        }
                    }
                });
            }
        }
    });
}

function FillStyles(styles) {
    if (styles == null || styles.length == 0) {
        $("#areaRecommend").find("ul").html("");
        $("#areaRecommend").hide();
    }
    else {
        var itemsHtml = "";
        for (var i = 0; i < styles.length; i++) {
            var curStyle = styles[i];
            var link = "http://www.m18.com/app/AdEntrance.aspx?from=GXTJ04&amp;targetURL=http://product.m18.com/" + curStyle.StyleType + "-" + curStyle.StyleId + ".htm";
            itemsHtml += "<li class=\"item-m\">"
					+ "<a href=\"" + link + "\" title=\"" + curStyle.ChineseName + "\" target=\"_blank\">"
						+ "<img height=\"120\" width=\"92\" class=\"item-m-pic\" src=\"" + curStyle.SuperMapImageUrl + "\" alt=\"" + curStyle.ChineseName + "\">"
						+ "<span class=\"item-m-title\">" + curStyle.ChineseName + "</span>"
					+ "</a>"
					+ "<p class=\"item-s-price\"><span>" + curStyle.WebSalePriceDisplay + "</span>" + (curStyle.GPPrice > 0 ? ("<em style=\"display:none;\" class=\"item-s-point\">+" + curStyle.GPPriceDisplay + "积分</em>") : "") + "</p>"
				+ "</li>";
        }
        $("#areaRecommend").find("ul").html(itemsHtml);
        $("#areaRecommend").show();
    }
}

function BuildPriceLink(url, min, max) {
    var start = url.lastIndexOf("/") + 1;
    var end = url.indexOf(".htm");
    var q = url.substring(start, end);

    var arr = q.split("-");
    arr[8] = min;
    arr[9] = max;
    var newq = arr.join("-");
    var newUrl = url.substring(0, url.lastIndexOf("/") + 1) + newq + url.substring(url.indexOf(".htm"), url.indexOf(".htm") + 4);
    var indHash = url.indexOf("#");
    if (indHash > 0) {
        var tmpHash = url.substring(indHash + 1);
        newUrl += "#" + tmpHash;
    }
    return newUrl;
}

function ElementsClick(obj) {
    try {
        if ($(obj).attr("id") == "SubPrice") {
            var url = $(obj).attr("oriHref");
            var price1 = $("#txtPrice1").val();
            var price2 = $("#txtPrice2").val();
            if (price1 != "" || price2 != "") {
                if (price1 != "" && price2 != "") {
                    price1 = parseInt(price1);
                    price2 = parseInt(price2);
                    if (price1 > price2) {
                        var tmp = price1;
                        price1 = price2;
                        price2 = tmp;
                    }
                }
                price1 = price1 == "" ? "N" : price1;
                price2 = price2 == "" ? "N" : price2;
                $(obj).attr("href", BuildPriceLink(url, price1, price2));
                return true;
            }
            else {
                $(obj).attr("href", BuildPriceLink(url, 'N', 'N'));
                return true;
            }
        }
        else {
            var pageNum = $("#txtPage").val();
            if (pageNum == ""
			|| pageNum == undefined) {
                return false;
            }
            var oldurl = $(obj).attr("href");
            var start = 0;
            var end = 0;
            var splitCount = 0;
            for (var i = 0; i < oldurl.length; i++) {
                var letter = oldurl.substring(i, i + 1);
                if (letter == "-") {

                    splitCount++;
                    if (splitCount == 4) {
                        start = i + 1;

                    }
                    else if (splitCount == 5) {
                        end = i - 1;
                    }
                }

            }
            var nowurl = oldurl.substring(0, start) + pageNum + oldurl.substring(end + 1);
            $(obj).attr("href", nowurl);
            return true;
        }
    }
    catch (ex) { }
}
function CheckNumber(object) {
    var isTxtPage = $(object).attr("id") == "txtPage";
    var txt = object.val();
    if (isTxtPage) {
        if (!CheckIntRegex(txt)) {
            object.val("");
        }
    }
    else {
        if (!CheckIntRegex(txt) && txt != "0") {
            object.val("");
        }
    }
}
//检测正整数
function CheckIntRegex(value) {
    var myreg = /^[1-9]\d*$/;
    return myreg.test(value);
}

function BindFilterToggle() {
    var allTm = $("div.branditem").find("li");
    if (allTm.length > 8) {
        var isClose = $("div.branditem").find("li:hidden").length > 0;
        var toggleLink = $("<a class=\"icobtn " + (isClose ? "ex" : "in") + "\" id=\"toggleTradeMark\" href=\"javascript:void(0);\">" + (isClose ? "展开" : "收起") + "</a>");
        $("div.branditem").find("dd").append(toggleLink);
    }

    $("#toggleTradeMark").click(
			function () {
			    if ($(this).hasClass("ex")) {
			        $(this).removeClass('ex');
			        $(this).addClass('in').text('收起');
			        $("ul.brandBox ").children('li:gt(7)').show();
			    }
			    else {
			        $(this).removeClass('in')
			        $(this).addClass('ex').text('展开');
			        $("ul.brandBox ").children('li:gt(7)').hide();
			    }
			}
		);
    var allPt = $("#propretyArea").find("div.prop-item");
    allPt.each(
		function () {
		    if ($(this).find("li").length > 7) {
		        var isClose = $(this).find("li:hidden").length > 0;
		        var toggleLink = $("<a class=\"icobtn " + (isClose ? "ex" : "in") + " toggleValues\" href=\"javascript:void(0);\">" + (isClose ? "展开" : "收起") + "</a>");
		        $(this).find("dd").append(toggleLink);
		    }
		}
	);
    if (allPt.length > 2) {
        var isClose = $("#propretyArea").find("div.prop-item:hidden").length > 0;
        var toggleLink = $("<div class=\"act-scroll proTypeChoose\" id=\"proTypeChoose\"><a href=\"javascript:void(0);\" class=\"" + (isClose ? "exscroll" : "inscroll") + " db\" id=\"toggleTypes\">" + (isClose ? "更多选项" : "精简选项") + "</a></div>");
        $("div.proditembox").append(toggleLink);
    }

    $("#toggleTypes").click(
				function () {
				    if ($(this).hasClass("inscroll")) {
				        $(this).removeClass('inscroll')
				        $(this).addClass('exscroll').text('更多选项');
				        $('.proTypeBox:gt(1)').hide();
				    }
				    else {
				        $(this).removeClass('exscroll')
				        $(this).addClass('inscroll').text('精简选项');
				        $('.proTypeBox:gt(1)').show();
				    }
				}
			);

    $(".toggleValues").click(
			function () {
			    if ($(this).hasClass("ex")) {
			        $(this).removeClass('ex');
			        $(this).addClass('in').text('收起');
			        $(this).prev().children('li:gt(6)').show();
			    }
			    else {
			        $(this).removeClass('in')
			        $(this).addClass('ex').text('展开');
			        $(this).prev().children('li:gt(6)').hide();
			    }
			}
		);
}

//SKU的click事件
function SKUChangeBind(styleId, skuId) {
    var thisli = $("li[styleId=" + styleId + "] .SkuColorSelect a[skuId=" + skuId + "]");
    var skuid = $(thisli).attr("skuId");

    //选中标志
    $("li[styleId=" + styleId + "] .SkuColorSelect li[class='cur']").attr("class", "");
    $("li[styleId=" + styleId + "] .SkuColorSelect a[skuId=" + skuid + "]").parent().attr("class", "cur");
    //换图片
    var skuImg = $(thisli).find("img").eq(0).attr("src");
    if (skuImg.indexOf("COLOR") > -1) {
        var newSrc = $(thisli).attr("imgName");
        $("li[StyleId=" + styleId + "] img").eq(0).attr("src", newSrc);

        //跟新链接,链接到单品页带SKU
        ChangeHrefBySkuId(styleId, skuId)
    }
};
//跟新链接,链接到单品页带SKU
function ChangeHrefBySkuId(styleId, skuId) {
    //图片链接
    var itemHref = $("li[StyleId=" + styleId + "] a.ForSkuLink").eq(0);
    //评论链接
    var commHref = $("li[StyleId=" + styleId + "] a.CommSkuLink").eq(0);
    //是否本来就带有SkuId
    var oldSkuId = itemHref.attr("href").indexOf("color=");
    var itemNewHref = "";
    //有老的SkuId则替换
    if (oldSkuId != undefined && oldSkuId > 0) {
        itemNewHref = itemHref.attr("href").substring(0, oldSkuId + 6) + skuId;
    }
    else {
        itemNewHref = itemHref.attr("href") + "?color=" + skuId;
    }
    itemHref.attr("href", itemNewHref);
    commHref.attr("href", itemNewHref + "#comment");
};


function GetAreaHotComment() {
    $.ajax({
        url: "http://comm.m18.com/comment/hotcomment.htm?from=list&size=8&class=" + (styleClassInfo.ClassId1 == null ? "" : styleClassInfo.ClassId1),
        dataType: "jsonp",
        success: function (data) {
            if (data.length > 0) {
                var itemsHtml = "";
                $.each(data, function (i, n) {
                    var tmpLink = "http://www.m18.com/app/AdEntrance.aspx?from=splbrmpl&amp;targetURL=" + "http://product.m18.com/p-" + n.styleid + ".htm";
                    itemsHtml += "<li class=\"item-s\">"
							+ "<div class=\"item-s-hd\">"
							+ "		<a title=\"" + unescape(n.name) + "\" href=\"" + tmpLink + "\" class=\"item-s-title\" target=\"_blank\">" + unescape(n.name) + "</a>"
							+ "		<p class=\"item-s-price\"><span>" + unescape(n.price).replace(/￥/, '') + "</span></p>"
							+ "	</div>"
							+ "	<a title=\"" + unescape(n.name) + "\" href=\"" + tmpLink + "\" class=\"item-s-pic\" target=\"_blank\"><img height=\"65\" width=\"50\" alt=\"\" src=\"" + n.image + "\"></a>"
							+ "	<div class=\"item-s-txt\">"
							+ "		<p class=\"item-s-name\"><a href=\"http://myshishang.m18.com/share/" + n.contactId + "-" + n.hmac + "-1.htm\">" + unescape(n.member) + "</a></p>"
							+ "		<p class=\"item-s-comm\"><a title=\"" + unescape(n.content) + "\" href=\"" + tmpLink + "\">" + unescape(n.content) + "</a></p>"
							+ "	</div>"
							+ "</li>";
                });
                $("#areaHotComment").find("ul").append(itemsHtml)
                $("#areaHotComment").show();
            }
        },
        error: function () {
        }
    });

}

function ProcessLastView() {
    $("#clearView").bind("click", function () {
        $.cookie("LastView", "", { expires: -1, path: "/", domain: "m18.com", secure: true });
        $("#areaLastView ul").hide();
        return false;
    });
    //1、异步读取cookie并展示
    if (typeof ($.cookie("LastView")) != "undefined"
		&& $.cookie("LastView") != null) {
        //获取cookie
        var viewedItemArray = $.cookie("LastView").split("$");
        //1. 读取Cookie
        //获取每次浏览记录的数组
        var viewedItemRetunArray = new Array();
        //使用Ajax方式
        //构建Ajax请求的参数
        var ids = ""
        for (var i in viewedItemArray) {
            //若当前浏览记录为空，则跳过进行下次循环
            if (viewedItemArray[i] == null
				|| viewedItemArray[i] == "") {
                continue;
            }
            ids += viewedItemArray[i] + ",";

        }
        if (ids.length > 0) {
            ids = ids.substring(0, ids.length - 1);
        }
        $.ajax({
            type: "GET",
            contentType: "application/json",
            url: "http://productutil.m18.com/LastView.aspx",
            data: "StyleIds=" + ids,
            dataType: "jsonp",
            success: function (result) {
                var itemsHtml = "";
                if (result
					&& result.IsSuccess
					&& result.ReturnValue
					&& result.ReturnValue.length > 0) {
                    for (var i = 0; i < result.ReturnValue.length; i++) {
                        var curStyle = result.ReturnValue[i];
                        var link = "http://www.m18.com/app/AdEntrance.aspx?from=ZJLL004&amp;targetURL=" + "http://product.m18.com/" + curStyle.StyleType + "-" + curStyle.StyleId + ".htm";
                        itemsHtml += "<li class=\"item-s\">"
										+ "<a title=\"" + curStyle.ChineseName + "\" href=\"" + link + "\" class=\"item-s-pic\" target=\"_blank\"><img height=\"65\" width=\"50\" alt=\"" + curStyle.ChineseName + "\" src=\"" + curStyle.LargeMapImageUrl + "\"></a>"
											+ "<div class=\"item-s-txt\">"
												+ "<a title=\"" + curStyle.ChineseName + "\" href=\"" + link + "\" class=\"item-s-title\" target=\"_blank\">" + curStyle.ChineseName + "</a>"
												+ "<p class=\"item-s-brand\">" + curStyle.TradeMarkName + "</p>"
												+ "<p class=\"item-s-price\"><span>" + curStyle.WebSalePriceDisplay + "</span>" + (curStyle.GPPrice > 0 ? ("<em class=\"item-s-point\">+" + curStyle.GPPriceDisplay + "积分</em>") : "") + "</p>"
											+ "</div>"
									+ "</li>";
                    }
                    $("#areaLastView").find("ul").append(itemsHtml)
                }
                $("#areaLastView").show();
            },
            error: function (result, status) {
                $("#areaLastView").show();
            }
        });
    }
}

/*  将滚动条滚动至当前Anchor位置
*/
function ScrollToTargetAnchor(id) {
    var object = document.getElementById(id);
    if (typeof (object) != "underfined" && object != null) {
        object.scrollIntoView();
    }
}

/* Mask滚动样式
*/
$(window).scroll(function () {
    if ($(window).scrollTop() > $("#J_lazyload").offset().top) {
        $("div.loadingmask-txt").removeClass("fixtop").addClass("fixtedload");
        if ($.browser.msie && $.browser.version == 6) {
            var ftop = $(window).scrollTop() - $("div.filterbox").offset().top;
            $("div.loadingmask-txt").css("top", ftop)
        }
    }
    else {
        $("div.loadingmask-txt").removeClass("fixtedload").addClass("fixtop");
    }

})

/*  记录Log
*/
function AddJsErrorLog(targetUrl, funName, content) {
    if ((targetUrl == null || targetUrl.length == 0) && (funName == null || funName.length == 0)) {
        return;
    }
    try {
        content += "-------BroswerInfo:" + navigator.appName + "--" + navigator.userAgent + "--" + navigator.appVersion + "--" + navigator.platform + "--" + navigator.javaEnabled() + "--" + navigator.browserLanguage + "--" + (document.charset ? document.charset : document.characterSet);
        $.get("Log.aspx", { targetUrl: encodeURI(targetUrl), funName: funName, content: escape(content) });
    }
    catch (ex) { }
}

function ChangePageTitle(pageTitle) {
    if (pageTitle != undefined && pageTitle != "") {
        document.title = pageTitle;
    }
}

/*  引入新的Js文件
*/
function ImportScriptionFile(src){
    var jsElement=document.createElement("script");
    jsElement.setAttribute("type","text/javascript");
    jsElement.setAttribute("src",src);
    document.getElementsByTagName("head")[0].appendChild(jsElement);
}